#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Demo Relying Party Account Handlers."""

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db

import logging

from lib import authn
from lib.loggable import loggable
from lib.error import handle_error

import model

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

class AccountHandler(webapp.RequestHandler):

    @authn.login_required 
    @loggable('show account') 
    def get(self):
          
      values = {
          'user': self.user
      }
      path = os.path.join(os.path.dirname(__file__), 'templates/account.html')
      self.response.out.write(template.render(path, values))   
      
class DeleteAddressHandler(webapp.RequestHandler):
    
    @authn.login_required
    @loggable('delete address')     
    def post(self):

      address_id = self.request.get('address_id')
      logging.debug('request to delete address %s' % address_id)
      if address_id is None or address_id == '':
        logging.error('no address id in the request present')
        handle_error(self)
        return

      logging.debug('retrieving address from the database')
      address = model.Address.get(db.Key(address_id))
      if address is None:
        logging.error('address not found in the database')
        handle_error(self)
        return
      logging.debug('address found - deleting')
      address.delete()
      logging.debug('address successfully deleted')
      session = self.session
      session.verified = False
      logging.debug('changed status of the session to UNVERIFIED')
      session.put()
      logging.debug('session stored within the database')
      self.redirect('/setup')          